import logging
import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import os
from datetime import datetime

from Config.config import email



def setup_logger():
    """初始化日志配置"""
    log_dir = "./logs"
    os.makedirs(log_dir, exist_ok=True)

    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler(f"{log_dir}/test_{datetime.now().strftime('%Y%m%d')}.log",encoding='utf-8'),

            logging.StreamHandler()
        ]
    )
    return logging.getLogger()


log = setup_logger()


def send_email(receiver, subject, content, attachment_path=None):
    """
    发送邮件
    :param receiver: 收件人列表
    :param subject: 邮件主题
    :param content: 邮件内容
    :param attachment_path: 附件路径
    """
    sender = email['sender']
    password = email['password']
    smtp_server = email['smtp']
    port = email['port']

    # 创建一个多部分消息并设置标题
    message = MIMEMultipart()
    message["From"] = sender
    message["To"] = ", ".join(receiver)
    message["Subject"] = subject

    # 添加邮件正文
    message.attach(MIMEText(content, "plain"))

    # 添加附件
    if attachment_path and os.path.exists(attachment_path):
        with open(attachment_path, "rb") as file:
            part = MIMEApplication(file.read(), Name=os.path.basename(attachment_path))
        # 在附件头部添加信息
        part['Content-Disposition'] = f'attachment; filename="{os.path.basename(attachment_path)}"'
        message.attach(part)

    # 创建安全的SSL上下文
    context = ssl.create_default_context()

    try:
        # 连接到SMTP服务器
        server = smtplib.SMTP_SSL(smtp_server, port, context=context)
        # 登录邮箱
        server.login(sender, password)
        # 发送邮件
        server.sendmail(sender, receiver, message.as_string())
        log.info("邮件发送成功")
    except Exception as e:
        log.error(f"邮件发送失败: {e}")
    finally:
        # 关闭连接
        if 'server' in locals():
            server.quit()